package com.suns.sharephoto.controller;

import com.alibaba.fastjson.JSON;
import com.suns.sharephoto.common.Result;
import com.suns.sharephoto.entity.User;
import com.suns.sharephoto.entity.WxLoginResponse;
import com.suns.sharephoto.mapper.UserMapper;
import com.suns.sharephoto.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
@CrossOrigin
@RequiredArgsConstructor
@Slf4j
public class AuthController {

    @Value("${wx.miniapp.appid}")
    private String appid;

    @Value("${wx.miniapp.secret}")
    private String secret;

    private final UserMapper userMapper;
    private final JwtUtil jwtUtil;

    @PostMapping("/wx/login")
    public Result<?> login(@RequestBody Map<String, String> params) {
        try {
            String code = params.get("code");
            log.info("收到登录请求，code: {}", code);
            
            if (code == null || code.isEmpty()) {
                return Result.error("code不能为空");
            }

            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appid, secret, code
            );
            
            log.info("请求微信接口URL: {}", url);

            // 调用微信接口
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpGet httpGet = new HttpGet(url);
                try (CloseableHttpResponse response = client.execute(httpGet)) {
                    String responseText = EntityUtils.toString(response.getEntity());
                    log.info("微信接口返回: {}", responseText);
                    
                    WxLoginResponse wxResponse = JSON.parseObject(responseText, WxLoginResponse.class);

                    if (wxResponse.getErrcode() != null) {
                        log.error("微信登录失败: {}", wxResponse.getErrmsg());
                        return Result.error("微信登录失败：" + wxResponse.getErrmsg());
                    }

                    // 查找或创建用户
                    User user = userMapper.findByOpenid(wxResponse.getOpenid());
                    if (user == null) {
                        log.info("新用户注册，openid: {}", wxResponse.getOpenid());
                        user = new User();
                        user.setOpenid(wxResponse.getOpenid());
                        userMapper.insert(user);
                    }

                    // 生成token
                    String token = jwtUtil.generateToken(user.getId());

                    // 返回结果
                    Map<String, Object> result = new HashMap<>();
                    result.put("token", token);
                    result.put("userInfo", user);

                    return Result.success(result);
                }
            }
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    @PostMapping("/wx/update")
    public Result<?> updateUserInfo(@RequestBody User userInfo, @RequestHeader("Authorization") String token) {
        try {
            // 验证token
            String tokenValue = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(tokenValue)) {
                return Result.error("无效的token");
            }

            // 获取当前用户ID
            Integer userId = jwtUtil.getUserIdFromToken(tokenValue);
            userInfo.setId(userId);

            // 更新用户信息
            userMapper.update(userInfo);
            return Result.success(userInfo);

        } catch (Exception e) {
            return Result.error("更新用户信息失败：" + e.getMessage());
        }
    }

    @GetMapping("/validate")
    public Result<?> validateToken(@RequestHeader("Authorization") String token) {
        try {
            String tokenValue = token.replace("Bearer ", "");
            if (!jwtUtil.validateToken(tokenValue)) {
                return Result.error("无效的token");
            }
            return Result.success(null);
        } catch (Exception e) {
            return Result.error("token验证失败");
        }
    }
} 